package com.ta.gulimall.order.config.rabbitmq.listener;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.ta.gulimall.common.utils.system.R;
import com.ta.gulimall.order.config.rabbitmq.MqQueueConstant;
import com.ta.gulimall.order.feign.WareFeignService;
import com.ta.gulimall.order.service.OrderService;
import com.ta.gulimall.order.view.entity.OrderEntity;
import com.ta.gulimall.order.view.vo.LockStoreRespVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = MqQueueConstant.STORE_UNLOCK_QUEUE)
public class StoreUnlockQueueConsume {
    @Autowired
    OrderService orderService;
    @Autowired
    WareFeignService wareFeignService;

    @RabbitHandler(isDefault = true)
    public void consume(Message message, Channel channel) throws IOException {
        String body = new String(message.getBody());
        LockStoreRespVo lockStoreRespVo = JSONUtil.toBean(body, LockStoreRespVo.class);

        OrderEntity orderEntity = orderService.getById(lockStoreRespVo.getOrderId());
        //订单回滚了
        if (orderEntity == null) {
            wareFeignService.unlockStore(lockStoreRespVo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        //订单关单
        if (orderEntity.getStatus().equals(4)) {
            wareFeignService.unlockStore(lockStoreRespVo);
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
